//
//  JVAutoNetDiagnosisMonitor.m
//  LeGaoCommon
//
//  Created by 颜小强 on 2019/3/25.
//  Copyright © 2019年 王卫. All rights reserved.
//

#import "JVAutoNetDiagnosisMonitor.h"
#import "JVPharosNetworkModel.h"
#import "JVMonitorCenter.h"

@interface JVAutoNetDiagnosisMonitor()

@property (nonatomic, strong) dispatch_source_t  timer;
@property (nonatomic, assign) NSUInteger         errorReqCount;
@property (nonatomic, assign) NSUInteger         requestCount;

@end

@implementation JVAutoNetDiagnosisMonitor

+ (instancetype)instance
{
    static JVAutoNetDiagnosisMonitor   *diagnosisMonitor;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        diagnosisMonitor = [[JVAutoNetDiagnosisMonitor alloc]init];
    });
    return diagnosisMonitor;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _isLaunching = NO;
        _errorReqCount = 0;
        _requestCount = 0;
    }
    return self;
}

- (void)startNetDiagnosis
{
    [self endNetDiagnosis];
    [self startTimer];
}

- (void)endNetDiagnosis
{
    self.errorReqCount = 0;
    self.requestCount = 0;
    [self stopTimer];
}

- (void)startTimer
{
    __weak JVAutoNetDiagnosisMonitor *_weakMonitor = self;
    NSTimeInterval interval = self.isLaunching?[self timerIntervalLaunching]:[self timerIntervalNormal];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, interval * NSEC_PER_SEC);
    dispatch_source_set_timer(self.timer, time, interval * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(self.timer, ^{
        __strong JVAutoNetDiagnosisMonitor *_strongMonitor = _weakMonitor;
        [_strongMonitor netDiagnosisAuto];
    });
    dispatch_resume(self.timer);
}

-(void)stopTimer {
    if(self.timer){
        dispatch_source_cancel(self.timer);
        self.timer = nil;
    }
}

- (void)netDiagnosisAuto
{
    if ([self isAutoDiagnosis]) {
        JVAutoNetDiagnosisMonitorBlock block = self.block;
        if (block) {
            block();
        }
    }
    //首次启动监控完成后，改成非首次启动时间监控
    if (self.isLaunching) {
        self.isLaunching = NO;
        [self endNetDiagnosis];
        [self startNetDiagnosis];
    }
    self.errorReqCount = 0;
    self.requestCount = 0;
}

- (BOOL)isAutoDiagnosis
{
    BOOL autoDiagnosis = NO;
    if (self.requestCount>=[self requestCountMin] && (self.errorReqCount/self.requestCount>=[self requestErrorCountRate])) {
        autoDiagnosis = YES;
    }
    return autoDiagnosis;
}

//累加接口数
- (void)addRequestCountWithError:(NSError *)error
{
    NSInteger code = error.code;
    if (code<0 || (code>401 && (code != 430 && code != 555))) {
        self.errorReqCount++;
    }
    
    self.requestCount++;
}

//首次监控timer时间
- (NSTimeInterval)timerIntervalLaunching
{
    NSArray *ary = [self netDiagnosisStrategy];
    return (ary.count>1)?[[ary objectAtIndex:0]floatValue]*60.:120;
}

//非首次监控timer时间
- (NSTimeInterval)timerIntervalNormal
{
    NSArray *ary = [self netDiagnosisStrategy];
    return (ary.count>1)?[[ary objectAtIndex:1]floatValue]*60.:300;
}

//请求总个数
- (NSInteger)requestCountMin
{
    NSArray *ary = [self netDiagnosisStrategy];
    return (ary.count>2)?[[ary objectAtIndex:2]integerValue]:10;
}

//请求错误率
- (float)requestErrorCountRate
{
    NSArray *ary = [self netDiagnosisStrategy];
    return (ary.count>3)?[[ary objectAtIndex:3]floatValue]:0.9;
}

- (NSArray *)netDiagnosisStrategy
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *values = [defaults objectForKey:@"backgroundNetDiag"];
    NSArray *ary = @[];
    if (values) {
        ary = [values componentsSeparatedByString:@"|"];
    }
    return ary;
}

@end
